package com.example.minicat.server;

import java.io.*;

public class Response {


    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }


    // 使用输出流输出指定字符串
    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }


    /**
     *
     * @param path  url，随后要根据url来获取到静态资源的绝对路径，进一步根据绝对路径读取该静态资源文件，最终通过
     *                  输出流输出
     *              /-----> classes
     */
    public void outputHtml(String path) throws IOException {
        // 获取静态资源文件的绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);

        // 输入静态资源文件
        File file = new File(absoluteResourcePath);
        if(file.exists() && file.isFile()) {
            // 读取静态资源文件，输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream);
        }else{
            // 输出404
            output(HttpProtocolUtil.getHttpHeader404());
        }

    }
    public void outputHtml(Request request,Mapper mapper) throws IOException {
        /**
         * 设置媒体类型
         */
        String contentType = "text/html";
        if (request.getUrl().endsWith(".png")){
            contentType = "image/png";
        }else if(request.getUrl().endsWith(".jpg") || request.getUrl().endsWith(".jpeg")){
            contentType = "image/jpeg";
        }else if(request.getUrl().endsWith(".pdf")){
            contentType = "application/pdf";
        }else if (request.getUrl().endsWith(".js")){
            contentType = "application/javascript";
        }else if(request.getUrl().endsWith(".css")){
            contentType = "text/css";
        }
        //先从webapps中查找,找不到就使用默认的
        for (Host host : mapper.getHosts()) {
            if (request.getHost().equalsIgnoreCase(host.getName()) || "localhost".equals(request.getHost())){
                File file = new File(host.getAppbase() + "/" + request.getUrl());
                if (file.exists() && file.isFile()){
                    StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream,contentType);
                    return;
                }
            }
        }
        outputHtml(request.getUrl());
    }
}
